package tako.wisers.com.android.apis.http;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import tako.wisers.com.android.apis.activity.Tako;
import tako.wisers.com.android.apis.database.SQListManager;
import tako.wisers.com.android.apis.item.SettingItem;
import tako.wisers.com.android.apis.parser.ConfXMLParser;
import tako.wisers.com.android.apis.parser.StationXMLParser;
import tako.wisers.com.android.apis.setting.SettingManager;
import tako.wisers.com.android.apis.util.Configration;
import tako.wisers.com.android.apis.util.Global;
import tako.wisers.com.android.apis.view.DialogManager;
import tako.wisers.com.android.apis.view.ViewNameIDConverse;

public class ConfLoadService {
	private Activity mActivity;
	private String mAppName;
	private String mTel;
	private static String xml_encode = "utf-8";
	private static String filte = "id=%d";

	public final static String HEADER_TEL_KEY = "tel";
	public final static String HEADER_APP_KEY = "app";
	public final static String HEADER_VERSION_KEY = "version";

	public ConfLoadService(String appName, String tel, Activity activity) {
		mActivity = activity;
		mAppName = appName;
		mTel = tel;
	}

	public ConfLoadService(String appName, String tel) {
		mAppName = appName;
		mTel = tel;
	}

	class ConfLoadThread extends Thread {
		private SQListManager sqlm;

		public ConfLoadThread(SQListManager sqlm) {
			this.sqlm = sqlm;
			start();
		}

		@Override
		public void run() {
			try {
				load();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}

		private void load() throws UnsupportedEncodingException {
			reloadConf(sqlm);
			toTako();
		}
	}

	private void toTako() {
		Context cxt = mActivity.getApplicationContext();
		Intent intent = new Intent();
		intent.setClass(cxt, Tako.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		cxt.startActivity(intent);
		mActivity.finish();
	}

	public synchronized static boolean makeDir(File file) {
		if (file.exists()) {
			return true;
		} else if (makeDir(file.getParentFile())) {
			return file.mkdir();
		} else {
			return false;
		}
	}

	@SuppressWarnings("unchecked")
	public boolean reloadConf(SQListManager sqlm)
			throws UnsupportedEncodingException {
		StationXMLParser.create();
		System.gc();
		String selection = String.format(filte, Global.CONF_DOWNLOAD_TYPE);
		List<SettingItem> settings = sqlm.select(SettingItem.class, false,
				selection);
		Configration conf = Configration.getInstance();
		String URLAttr = conf.getProperty(Global.CONF_ATTR);
		String defaultHost = conf.getProperty(Global.CONF_HOST_DEFAULT);
		String URLModel = defaultHost + URLAttr;
		SettingItem confSetting = new SettingItem(Global.CONF_DOWNLOAD_TYPE);
		if (settings.size() > 0) {
			confSetting = settings.get(0);
			URLModel = confSetting.getHost() + URLAttr;
		}

		String url = String.format(URLModel, mTel, mAppName);
		HttpGeter geter = new HttpGeter(url);
		String version = geter.getHeader(HEADER_VERSION_KEY);
		String localVersion = confSetting.getVersion();

		System.gc();
		SettingManager sm = SettingManager.getInstance();
		try {
			if ((version == null) || (localVersion != null && localVersion.equalsIgnoreCase(version))) {
				String xml = confSetting.getXml();
				
				if(xml == null){
					return false;
				}

				ConfXMLParser.create(true, new ByteArrayInputStream(xml
						.getBytes(xml_encode)));

				sm.put(confSetting.getId(), confSetting);
				return false;
			}

			String xml = geter.getContent();
			ConfXMLParser.create(false, new ByteArrayInputStream(xml
					.getBytes(xml_encode)));
			System.gc();
			if (confSetting.getHost() == null) {
				confSetting.setHost(defaultHost);
			}
			confSetting.setVersion(version);
			confSetting.setXml(xml);
			List objlist = new ArrayList();
			objlist.add(confSetting);
			sqlm.update(objlist, "id=" + Global.CONF_DOWNLOAD_TYPE, false);
			System.gc();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}finally{
			geter.close();
		}

		sm.put(confSetting.getId(), confSetting);
		return true;
	}

	public void loadConf() {
		SQListManager sqlm = SQListManager.getInstance();
		new ViewNameIDConverse();
		Configration.getInstance();
		new ConfLoadThread(sqlm);
	}
	
}
